# -*- coding: utf-8 -*-
"""
Created on Wed Feb 11 18:08:35 2015

@author: aaron
"""

import tornado
import json
from tornado import web
from tornado import websocket
import os
import time
import dbopt
import chatcert

cert = chatcert.chatcert()
dbc = dbopt.dbopt()
 
settings = {
    "static_path": os.path.join(os.path.dirname(__file__), "static"),
    "db":dbc,
}
class BaseHandler(web.RequestHandler):
    def get_cookie_user(self):
        user =  (self.get_cookie("user"),self.get_cookie('time'))
        return user
    def prepare(self):
        self.db = self.settings['db']
    def get_online(self):
        online = self.db.get_online()
        return online
class LoginHandler(BaseHandler):
    def get(self):
        self.render("login.html")
    def post(self):
        user = self.get_argument("username")
        self.set_cookie("user",user)
        self.set_cookie("time",str(time.time()))
        self.set_cookie("room_id",'5216')
        self.redirect("/index")
class IndexHandler(BaseHandler):
    def get(self):
        user = self.get_cookie_user()
        print user
        if user[0]=='' or not user[0]:
            self.write("please login!!!!")
            time.sleep(10)
            self.redirect('/')
        self.render("index.html",user=user[0],online = len(self.get_online()))
class login_websocketHandler(websocket.WebSocketHandler):
    def open(self):
        cert.online(self.get_cookie('user'),self.get_cookie('room_id'),self)
    def on_close(self):
        cert.outline(self.get_cookie('user'),self)
    def on_message(self,message):
        cert.notifycallbacks()
        print message
class room_websocketHandler(websocket.WebSocketHandler):
    def open(self):
        print self.get_cookie('user')+" enter " + self.get_cookie('room_id')
        cert.user_enter_room(self.get_cookie('user'),self.get_cookie('room_id'),self)
    def on_close(self):
        print self.get_cookie('user')+" quit " + self.get_cookie('room_id')
        cert.user_leave_room(self.get_cookie('user'),self.get_cookie('room_id'),self)
    def send_roomate(self,roomate):
        self.write_message(roomate)
class chat_websocketHandler(websocket.WebSocketHandler):
    def open(self):
        cert.add_chat(self)
        print self.get_cookie('user')+'added chat'
    def on_close(self):
        cert.leave_chat(self)
        print self.get_cookie('user')+'leave chat'
        chat_message = {'user':self.get_cookie('user'),'info':self.get_cookie('user')+" leave the room",'room_id':self.get_cookie('room_id'),'time':time.time()}
        messageJson = json.dumps(chat_message)
        print messageJson
        cert.blocast_chat(messageJson)
    def on_message(self,message):
        chat_message = {'user':self.get_cookie('user'),'info':message,'room_id':self.get_cookie('room_id'),'time':time.time()}
        messageJson = json.dumps(chat_message)
        print messageJson
        cert.blocast_chat(messageJson)
        
application = web.Application([
        (r'/',LoginHandler),
        (r'/index',IndexHandler),
        (r'/login_socket',login_websocketHandler),
        (r'/room_socket',room_websocketHandler),
        (r'/chat_socket',chat_websocketHandler),
],**settings)
if __name__ == "__main__":
    application.listen(8088)
    tornado.ioloop.IOLoop.instance().start()        